package leetcode.jianzhioffer;

/**
 * @program: datastructureandalogorithm
 * @description:
 * @author: hmx
 * @create: 2021-11-09 23:12
 **/
public class JianZhiOffer15 {

    /*public int hammingWeight(int n) {
        int res = 0;
        for (int i = 0; i < 32; i++) {
            if ((n & (1 << i)) != 0) {
                res++;
            }
        }
        return res;
    }*/

    public int hammingWeight(int n) {
        int res = 0;
        while (n != 0) {
            //n & n-1就是将的二进制位中的最低位的 11 变为 00 之后的结果。
            n &= n - 1;
            res++;
        }
        return res;
    }

}
